import logging
import os
import sys
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import yaml
import time
from datetime import datetime

from app.api.router import router

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)

logger = logging.getLogger("main")

# 创建FastAPI应用
app = FastAPI(
    title="AI资讯聚合与分析平台",
    description="用于收集、分析和推荐AI领域最新动态的API",
    version="0.1.0",
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应替换为实际的前端域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 加载配置
def load_config():
    try:
        config_path = os.environ.get('CONFIG_PATH', 'config.yml')
        logger.info(f"Loading config from {config_path}")
        
        with open(config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
            
        return config
    except Exception as e:
        logger.error(f"Failed to load config: {str(e)}")
        return {}

# 中间件
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

# 全局错误处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"Global exception: {str(exc)}")
    return JSONResponse(
        status_code=500,
        content={"status": "error", "message": f"服务器错误: {str(exc)}"}
    )

# 挂载API路由
app.include_router(router, prefix="/api")

# 根路径
@app.get("/")
async def root():
    return {
        "name": "AI资讯聚合与分析平台",
        "version": "0.1.0",
        "api_docs": "/docs",
        "api_base": "/api",
        "current_time": datetime.now().isoformat()
    }

# 健康检查
@app.get("/health")
async def health():
    return {"status": "ok", "timestamp": datetime.now().isoformat()}

# 主入口
if __name__ == "__main__":
    import uvicorn
    
    config = load_config()
    api_config = config.get('api', {})
    
    host = api_config.get('host', '0.0.0.0')
    port = int(api_config.get('port', 8000))
    workers = int(api_config.get('workers', 1))
    
    logger.info(f"Starting API server at {host}:{port} with {workers} workers")
    
    uvicorn.run(
        "app.main:app", 
        host=host, 
        port=port, 
        reload=True,
        workers=workers
    ) 